package com.example.practice.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.practice.model.User;
import com.example.practice.utils.HttpUrlUtil;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Objects;

/**
 * TODO
 *
 * @author zgq
 * @date 2020/10/21 13:59
 */
@RestController
@RequestMapping("/url")
public class UrlController {

    @PostMapping("/postUrl1")
    public String postUrl1(@RequestBody User req) {
        System.out.println(req);
        User user = new User().setName("postUrl1").setId(001).setGender("男");
        return JSONObject.toJSONString(user);
    }

    @GetMapping("/getUrl1")
    public String getUrl1() {
        User user = new User().setName("getUrl1").setId(001).setGender("女");
        return JSONObject.toJSONString(user);
    }

    @GetMapping("/practiceHttp")
    public String practiceHttp(String type, String url) throws IOException {
        User user = new User().setName("hahahhaha").setId(001).setGender("男");
        HttpURLConnection httpUrlConnection = HttpUrlUtil.connUrl(type, url, null, user);
        if (Objects.isNull(httpUrlConnection)) {
            return "发送请求失败";
        }
        int responseCode = httpUrlConnection.getResponseCode();
        System.out.println(responseCode);

        // 读取结果
        String s = HttpUrlUtil.readHttpInputStream(httpUrlConnection.getInputStream());
        System.out.println(s);
        return "ok";
    }
}
